﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.GamerServices;
using Lidgren.Network;
using Tetris_AntiGravity;
using Microsoft.Xna.Framework;
using Tetris_AntiGravity.network;

namespace GameStateManagement
{
    class ConnectionScreen : MenuScreen
    {

        protected NetClient client;
        Server servidor;
        
        public ConnectionScreen()
            : base("Connection")
        {
            MenuEntry serveGameMenuEntry = new MenuEntry("Serve a Game");
            MenuEntry connectMenuEntry = new MenuEntry("Connect to a Game");
            MenuEntry back= new MenuEntry("Back");

            serveGameMenuEntry.Selected += ServeMenuEntrySelected;
            connectMenuEntry.Selected += ConnectMenuEntrySelected;
            back.Selected += OnCancel;

            MenuEntries.Add(serveGameMenuEntry);
            MenuEntries.Add(connectMenuEntry);
            MenuEntries.Add(back);

        }

        void ConnectMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            /*
            if (!Guide.IsVisible)
            {
                string title = "Connect";
                string description = "Enter game´s name";
                string defaultText = "";

                Guide.BeginShowKeyboardInput(0, title, description, defaultText,
                                                          GetServerName, null);
            }
             */
            CrearCliente("Tetris");
                
        }


        void ServeMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            /*
            if (!Guide.IsVisible)
            {
                string title = "Connect";
                string description = "Enter game´s name";
                string defaultText = "";

                Guide.BeginShowKeyboardInput(0, title, description, defaultText,
                                                          GetTypedChars, null);
            }
             */
            CrearServidor("Tetris");
            
        }


        protected void GetTypedChars(IAsyncResult r)
        {
            String nombre = Guide.EndShowKeyboardInput(r);
            CrearCliente(nombre);
            
        }

        public void CrearCliente(String nombre, String servidor){
            NetPeerConfiguration config = new NetPeerConfiguration("Tetris");
            config.EnableMessageType(NetIncomingMessageType.DiscoveryResponse);

            client = new NetClient(config);
            client.Start();

            if (servidor.Equals(""))
            {
                client.DiscoverLocalPeers(14242);
            }

            else
            {
                client.Connect(servidor, 14242);
            }

            NetIncomingMessage msg;
            while (client.ConnectionStatus == NetConnectionStatus.Disconnected)
            {
                msg = client.ReadMessage();
                if (msg != null)
                {
                    switch (msg.MessageType)
                    {
                        case NetIncomingMessageType.DiscoveryResponse:
                            // just connect to first server discovered
                            client.Connect(msg.SenderEndpoint);
                            break;
                    }
                }
            }

            LoadingScreen.Load(ScreenManager, true, 0,
                               new GameplayScreen(client));
        }

        public void CrearCliente(string nombre)
        {
            CrearCliente(nombre, "");
        }

        protected void GetServerName(IAsyncResult r)
        {
            String nombre = Guide.EndShowKeyboardInput(r);
            CrearServidor(nombre);

        }

        private void CrearServidor(string nombre){
            servidor = new Server("Tetris", this);
            servidor.inicializarServidor();
            const string message = "Waiting for a connection";
            ConnectionBoxScreen connectionBox = new ConnectionBoxScreen(message);
            connectionBox.Cancelled += CancelarConnectionBox;
            ScreenManager.AddScreen(connectionBox, 0);
        }

        private void CancelarConnectionBox(object sender, PlayerIndexEventArgs e)
        {
            servidor.ApagarServidor();
        }

    }
}
